<?php
/**
 * Created by PhpStorm.
 * User: DongYao
 * Date: 2017/12/8
 * Time: 上午11:01
 */

namespace XmtApp\Modules\Admin\Controllers\Api;


use App\Http\Requests\TagPost;
use App\Http\Resources\TagsResource;
use App\Tables\Tag;
use XmtApp\Modules\Admin\Controllers\Controller;
use Illuminate\Http\Request;

class TagController extends Controller
{
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取标签列表
     * @param Request $request
     * @return Categories
     */
    public function index(Request $request)
    {
        $table = new Tag();

        if ($request->has('keyword')) {
            $table = $table->where('name', 'like', "%{$request->keyword}%");
        }

        if ($request->has('ids')) {
            $tag_ids = array_filter(explode(',', $request->ids));
            if (is_array($tag_ids)) {
                $table = $table->whereIn('id', $tag_ids);
            }
        }

        if ($request->has('page')) {
            $data = $table->paginate($request->header('pageSize'));
        } else {
            $data = $table->get();
        }

        return new TagsResource($data);
    }

    /**
     * 添加标签
     * @param TagPost $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(TagPost $request)
    {
        $data = $request->all(['name']);

        $table = new Tag($data);

        $res = $table->save();
        if ($res) {
            return response()->json(ajax_return(true, '添加成功', $table->toArray()));
        } else {
            return response()->json(ajax_return(false, '添加失败'));
        }
    }

    /**
     * 修改标签
     * @param $id
     * @param TagPost $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function update($id, TagPost $request)
    {
        $data = $request->all(['name']);
        $table = new Tag();

        $res = $table->where('id', $id)->update($data);
        if ($res) {
            return response()->json(ajax_return(true, '修改成功', $table->toArray()));
        } else {
            return response()->json(ajax_return(false, '修改失败'));
        }
    }

    /**
     * 删除标签
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $res = Tag::destroy($id);
        if ($res) {
            return response()->json(ajax_return(true, '删除成功'));
        } else {
            return response()->json(ajax_return(false, '删除失败'));
        }
    }
}